package com.eian.boot.common.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 敏感数据脱敏工具类
 *
 * @author alex.meng
 */
public class SensitiveDataMasker {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 敏感字段列表
     */
    private static final List<String> SENSITIVE_FIELDS = Arrays.asList(
            "password", "pwd", "passWord", "oldPassword", "newPassword",
            "idCard", "bankCard", "creditCard"
    );

    /**
     * 脱敏JSON字符串中的敏感信息
     */
    public static String maskJson(String json) {
        if (StringUtils.isBlank(json)) {
            return json;
        }

        try {
            JsonNode jsonNode = OBJECT_MAPPER.readTree(json);
            maskNode(jsonNode);
            return OBJECT_MAPPER.writeValueAsString(jsonNode);
        } catch (Exception e) {
            // 如果解析失败，返回原字符串
            return json;
        }
    }

    /**
     * 递归脱敏JSON节点
     */
    private static void maskNode(JsonNode node) {
        if (node == null || !node.isObject()) {
            return;
        }

        ObjectNode objectNode = (ObjectNode) node;
        objectNode.fieldNames().forEachRemaining(fieldName -> {
            JsonNode fieldValue = objectNode.get(fieldName);

            // 如果是敏感字段，进行脱敏
            if (SENSITIVE_FIELDS.contains(fieldName)) {
                objectNode.put(fieldName, "******");
            }
            // 如果是对象，递归处理
            else if (fieldValue.isObject()) {
                maskNode(fieldValue);
            }
            // 如果是数组，遍历处理
            else if (fieldValue.isArray()) {
                for (JsonNode arrayItem : fieldValue) {
                    maskNode(arrayItem);
                }
            }
        });
    }

    /**
     * 手机号脱敏：保留前3后4位
     */
    public static String maskPhone(String phone) {
        if (StringUtils.isBlank(phone) || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }

    /**
     * 邮箱脱敏：保留前2位和@后面的域名
     */
    public static String maskEmail(String email) {
        if (StringUtils.isBlank(email) || !email.contains("@")) {
            return email;
        }
        String[] parts = email.split("@");
        if (parts[0].length() <= 2) {
            return "**@" + parts[1];
        }
        return parts[0].substring(0, 2) + "****@" + parts[1];
    }

    /**
     * 身份证号脱敏：保留前6后4位
     */
    public static String maskIdCard(String idCard) {
        if (StringUtils.isBlank(idCard) || idCard.length() < 10) {
            return idCard;
        }
        return idCard.substring(0, 6) + "********" + idCard.substring(idCard.length() - 4);
    }
}


